package main;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import dao.ProxyConfig;
import dao.Result;
import okhttp3.Response;
import utils.LoggerUtile;
import utils.OkHttpClientUtils;
import utils.V8Utils;

import java.io.IOException;
import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo {
    private String cookie1;
    private  String xDatadomeClientid;

    String userAgent;
    ProxyConfig proxyConfig;
    Proxy proxy = null;
    static LoggerUtile logger =LoggerUtile.getLogger("garenaJava-app");

    public void getVpnIp2(){
        System.out.println("开始获取快代理ip");
        userAgent = String.valueOf(UUID.randomUUID());
        String url = "https://api.uggame.com/api/v1/security/common/proxyKD";
        JSONObject jsonObject = new JSONObject();
        try {
            Response response = OkHttpClientUtils.doPost(url,jsonObject.toJSONString());
            String resultStr = response.body().string();
            JSONObject parse = JSONObject.parseObject(resultStr);
            JSONObject data = (JSONObject) parse.get("data");
            if (data == null){
                System.out.println("data为空");
//                logger.info("data为空");
                return;
            }

            String ip = data.getString("ip");
            int port = data.getIntValue("port");
            System.out.println("成功获取vpn ip:"+ip+",port:"+port);
//                logger.info("成功获取vpn ip:"+ip+",port:"+port+",adr:"+adr);
            proxyConfig = new ProxyConfig(ip, port);
            proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyConfig.getIp(),proxyConfig.getPort()));

            java.net.Authenticator.setDefault(new java.net.Authenticator() {
                private PasswordAuthentication authentication = new PasswordAuthentication("d3428219915", "yb134jr2".toCharArray());
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return authentication;
                }
            });

            /*String body = HttpRequest.get("http://web.juhe.cn/finance/stock/hs")
                    .setProxy(proxy)
                    .execute().body();
            System.out.println("股票数据："+body);*/
            getClientID();
//            getDatadomeCode(1);
        } catch (IOException e) {
            System.out.println("请求vpn ip报错:"+e.getMessage());
//            logger.info("请求vpn ip报错:"+e.getMessage());
        }

    }

    public void getVpnIp(){
        try {
            userAgent = String.valueOf(UUID.randomUUID());
            /*String body = HttpRequest.get("http://www.zdopen.com/ShortS5Proxy/GetIP/?api=202204191050355128&akey=3d75e4a57eb17fc2&count=1&timespan=5&type=3")
                    .execute().body();*/
            String body = HttpRequest.get("http://api.91http.com/v1/get-ip?trade_no=B512532839538&secret=xkOM7C2dL5oX9458&num=1&protocol=2&format=json&sep=1&filter=1")
                    .execute().body();
            JSONObject Odata = (JSONObject) JSONObject.parse(body);
            JSONObject data = (JSONObject) Odata.get("data");
            if (data == null){
                System.out.println("data为空");
//                logger.info("data为空");
                return;
            }
            if (data.get("proxy_list") != null){
                JSONObject proxyObj = data.getJSONArray("proxy_list").getJSONObject(0);
                String ip = proxyObj.getString("ip");
                int port = proxyObj.getIntValue("port");
                String adr = proxyObj.getString("adr");
                System.out.println("成功获取vpn ip:"+ip+",port:"+port+",adr:"+adr);
//                logger.info("成功获取vpn ip:"+ip+",port:"+port+",adr:"+adr);
                proxyConfig = new ProxyConfig(ip, port);
                proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyConfig.getIp(),proxyConfig.getPort()));
                getClientID();
            }
        } catch (Exception e){
            System.out.println("请求vpn ip报错:"+e.getMessage());
//            logger.info("请求vpn ip报错:"+e.getMessage());
        }
    }

    public void getClientID() { //3.2datadome
//        logger.info("开始请求获取datadome...");
//        System.out.println("开始请求获取datadome...");

        cookie1 = getDomeCookies(null);
        if (cookie1 == null) {
            return ;
        }
        System.out.println("获取到cookie:"+cookie1);

//        logger.info("获取到cookie:"+cookie1);
        xDatadomeClientid = cookie1.split(";")[0].split("=")[1];
        prelogin();
    }

    public String getDomeCookies(String cid) {
        try {
            String jspl = V8Utils.getJspl(cid == null ? "" : cid);
            String eventCounters = null;
            String jsType = null;
            if (cid == null) {
                eventCounters = "[]";
                jsType = "ch";
            } else {
                eventCounters = "{\"mousemove\":161,\"click\":0,\"scroll\":0,\"touchstart\":0,\"touchend\":0,\"touchmove\":0,\"keydown\":0,\"keyup\":0}";
                jsType = "le";
            }
            String ddk = "AE3F04AD3F0D3A462481A337485081";
            String Referer = "https%3A%2F%2Fsso.garena.com%2Funiversal%2Flogin%3Fapp_id%3D10100%26redirect_uri%3Dhttps%253A%252F%252Faccount.garena.com%252F%26locale%3Den-SG";
            String request = "%2Funiversal%2Flogin%3Fapp_id%3D10100%26redirect_uri%3Dhttps%253A%252F%252Faccount.garena.com%252F%26locale%3Den-SG";
            String responsePage = "origin";
            String ddv = "4.46.0-next";
            String body = String.format("jspl=%s&eventCounters=%s&jsType=%s&cid=%s&ddk=%s&Referer=%s&request=%s&responsePage=%s&ddv=%s", jspl, URLEncoder.encode(eventCounters), jsType, cid, ddk, URLEncoder.encode(Referer), URLEncoder.encode(request), responsePage, ddv);
            if (cid == null) {
                body = String.format("jspl=%s&eventCounters=%s&jsType=%s&ddk=%s&Referer=%s&request=%s&responsePage=%s&ddv=%s", jspl, URLEncoder.encode(eventCounters), jsType, ddk, URLEncoder.encode(Referer), URLEncoder.encode(request), responsePage, ddv);
            }
            System.out.println("开始请求获取datadome...");
//            logger.info("开始请求获取datadome...");

            /*HttpRequest winhttp = HttpRequest.post("https://dd.garena.com/js/");
            winhttp.header("content-type", "application/x-www-form-urlencoded");
            winhttp.header("priority", "u=1, i");
            winhttp.header("sec-ch-ua", "\"Google Chrome\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"");
            winhttp.header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36");
            winhttp.body(body);
            String reslut = winhttp.setReadTimeout(40000)
                    .setConnectionTimeout(40000)
                    .timeout(40000)
                    .setProxy(proxy)
                    .executeAsync()
                    .body();*/
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("content-type", "application/x-www-form-urlencoded");
            headerMap.put("priority", "u=1, i");
            headerMap.put("sec-ch-ua", "\"Google Chrome\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"");
            headerMap.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36");

            Response response = OkHttpClientUtils.doFormPost("https://dd.garena.com/js/", headerMap, body, proxy);
            String reslut = response.body().string();

//            logger.info("获取datadome结果" + reslut);
            System.out.println("获取datadome结果" + reslut);

            String cookies = JSONObject.parseObject(reslut).getString("cookie");
            return cookies;
        } catch (Exception e) {
            System.out.println("获取datadome请求异常" + e.getMessage());

//            logger.error("获取datadome请求异常" + e.getMessage());
            return null;
        }

    }

     Result prelogin(){ //3.2预登录
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Host", "sso.garena.com");
            headers.put("Connection", "keep-alive");
            headers.put("sec-ch-ua-platform", "\"Windows\"");
            headers.put("User-Agent", userAgent);
            headers.put("Accept", "application/json, text/plain, */*");
            headers.put("sec-ch-ua", "\"Microsoft Edge\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"");
            headers.put("sec-ch-ua-mobile", "?0");
            headers.put("Sec-Fetch-Site", "same-origin");
            headers.put("Sec-Fetch-Mode", "cors");
            headers.put("Sec-Fetch-Dest", "empty");
            headers.put("Referer", "https://sso.garena.com/universal/login?app_id=10100&redirect_uri=https%3A%2F%2Faccount.garena.com%2F&locale=en-SG");
            headers.put("Accept-Language", "zh-CN,zh;q=0.9");
            headers.put("Cookie", cookie1);
            Response response = OkHttpClientUtils.doGetByProxy("https://sso.garena.com/api/prelogin?app_id=10100&account=" + "hienthdtn" + "&format=json&id=" + System.currentTimeMillis(), headers, proxy);
            JSONObject parse = (JSONObject) JSONObject.parse(response.body().string());
            //logger.info("预登录param cookie1:" + cookie1);
            logger.info("预登录结果" + parse);
            if (parse.get("error") != null && parse.get("error").equals("error_require_datadome_cookie")) {
                logger.info("error_require_datadome_cookie");
                return new Result(24, "equire_datadome_cookie", parse.get("error"));
            }

            return new Result(22, "预登录成功", parse);
        } catch (Exception e) {
            logger.error("预登录处理异常" + e.getMessage());
            return new Result(-1, "预登录处理异常" + e.getMessage(), e.getMessage());
        }
    }

}
